package cn.miketsu.iced;

import cn.miketsu.iced.config.DataBase;
import cn.miketsu.iced.reflect.MysqlCrateTable;
import cn.miketsu.iced.uitl.JdbcUtil;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 主类
 *
 * @author wangzefeng
 * @since 1.0-SNAPSHOT
 */
public final class IcedStater {

    /**
     * 执行建表操作
     *
     * @throws Exception
     * @author wangzefeng
     * @since 1.1-SNAPSHOT
     */
    public static void excute() throws Exception {
        Properties prop = new Properties();
        InputStream inputStream = IcedStater.class.getClassLoader().getResourceAsStream("iced.properties"); //properties
        prop.load(inputStream);
        DataBase dataBase = new DataBase(prop.getProperty("driver"), prop.getProperty("url"),
                prop.getProperty("username"), prop.getProperty("password"));
        if (prop.getProperty("driver") == null || prop.getProperty("driver").equals("")) {
            dataBase.autoConfigDriver();
        }
        if (inputStream != null) {
            inputStream.close();
        }
        excute(dataBase, prop.getProperty("packageName"));
    }

    /**
     * 执行建表操作
     * 本方法将于2.0版本将变为私有
     * 1.2版本-支持传入多个包名，用英文逗号,隔开
     *
     * @param dataBaseConfig 数据库配置对象 {@link cn.miketsu.iced.config.DataBase}
     * @param packageName    model所在包的包名
     * @throws Exception
     * @author wangzefeng
     * @since 1.0-SNAPSHOT
     */
    @Deprecated
    public static void excute(DataBase dataBaseConfig, String packageName) throws Exception {
        JdbcUtil.loadConfig(dataBaseConfig);
        String[] pn=packageName.split(",");
        List<String> list = new ArrayList<>();
        for (String value:pn) {
            list.addAll(MysqlCrateTable.create(value));
        }
        Connection con = null;
        Statement stmt = null;
        try {
            con = JdbcUtil.getConnection();
            con.setAutoCommit(true);
            stmt = con.createStatement();
            for (String s : list) {
                stmt.execute(s);
            }
        } finally {
            JdbcUtil.closeResource(stmt, con);
        }
    }
}
